/**
 * Copyright (c) 2009, http://www.softwareinlife.com. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, 
 * with or without modification, are permitted provided that 
 * the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the http://www.softwareinlife.com nor the names of its 
 *    contributors may be used to endorse or promote products derived from 
 *    this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE SOFTWAREINLIFE AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.softwareinlife.vision.android.ux.plan;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.softwareinlife.vision.android.R;
import com.softwareinlife.vision.android.data.dao.PlanDAO;
import com.softwareinlife.vision.android.data.exceptions.DatabaseConnectionException;
import com.softwareinlife.vision.android.data.exceptions.PlanUpdateException;
import com.softwareinlife.vision.android.data.exceptions.VisionReadException;
import com.softwareinlife.vision.android.data.exceptions.VisionUpdateException;

import com.softwareinlife.vision.android.data.model.PlanModel;
import com.softwareinlife.vision.android.ux.UXConstants;
import com.softwareinlife.vision.android.ux.schedule.CreateScheduleActivity;
import com.softwareinlife.vision.android.ux.schedule.ReadScheduleActivity;
import com.softwareinlife.vision.android.ux.start.VisionSoftwareMenuActivity;
import com.softwareinlife.vision.android.ux.util.ColorUtility;
import com.softwareinlife.vision.android.ux.util.SharedPreferenceUtility;
import com.softwareinlife.vision.android.ux.vision.ReadVisionActivity;

public class ReadPlanActivity extends Activity {

	/**
	 * Menu Dialog
	 */
	private Dialog menuDialog = null;

	/**
	 * Selected ID
	 */
	private int selectedIds = 0;

	/**
	 * Selected Menu
	 */
	private int seletedMenu = -1;

	/**
	 * Plan List
	 */
	private List<PlanModel> list = null;

	/**
	 * Plan List Layout
	 */
	private LinearLayout planListLinearLayout = null;

	/**
	 * On Create
	 */
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.plan_read);

		// Load Data
		loadListData();

		// Init Memebers
		initMemebers();

		// draw Data
		drawData();

	}

	private void initMemebers() {
		// Get Plan List
		planListLinearLayout = (LinearLayout) findViewById(R.id.planListLinearLayout);
	}

	/**
	 * Draw List
	 */
	private void drawData() {
		// Layout Parameters
		LinearLayout.LayoutParams planRowLinearLayoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		
		planRowLinearLayoutParams.setMargins(5, 2, 5, 2);

		for (int i = 0; i < list.size(); i++) {
			PlanModel plan = list.get(i);

			// Date Check
			if (plan != null
					&& (plan.getTitle() != null && plan.getTitle().length() > 0)
					&& (plan.getDesc() != null && plan.getDesc().length() > 0)) {

				// Create Row //////////////////////////////////////////////
				LinearLayout planRowLinearLayout = new LinearLayout(
						getApplicationContext());
				planRowLinearLayout.setId(plan.getIds());
				planRowLinearLayout.setClickable(true);
				planRowLinearLayout.setGravity(Gravity.CENTER);
				planRowLinearLayout.setLayoutParams(planRowLinearLayoutParams);
				planRowLinearLayout.setBackgroundColor(R.color.list_color);
				planRowLinearLayout.setClickable(true);

				// Row Event
				planRowLinearLayout.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						System.out.println("Vision ID is " + v.getId());

						showDialog(v.getId());
					}
				});

				// Blueprint(number + background color)
				TextView blueprintTextView = new TextView(
						getApplicationContext());
				blueprintTextView.setTextColor(R.color.string_color);
				blueprintTextView.setText("" + plan.getIds());
				blueprintTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f);
				blueprintTextView.setWidth(40);
				blueprintTextView.setHeight(40);
				blueprintTextView.setBackgroundResource(R.color.button_color2);
				blueprintTextView.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);

				// Add View //////////////////////////////////////////////
				planRowLinearLayout.addView(blueprintTextView);

				LinearLayout planContentLinearLayout = new LinearLayout(
						getApplicationContext());
				planContentLinearLayout.setId(plan.getIds());
				planContentLinearLayout.setClickable(true);
				planContentLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
				planContentLinearLayout
						.setLayoutParams(planRowLinearLayoutParams);
				planContentLinearLayout.setOrientation(LinearLayout.VERTICAL);
				planContentLinearLayout
						.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								System.out.println("Vision ID is " + v.getId());
								showDialog(v.getId());
							}
						});

				// Plan Title Text View
				TextView titleTextView = new TextView(getApplicationContext());
				titleTextView.setText(plan.getTitle());
				titleTextView.setTextSize(15);
				titleTextView.setBackgroundResource(R.color.string_color);
				titleTextView.setTextColor(R.color.button_color1);
				titleTextView.setPadding(2, 0, 2, 0);

				// Add View
				planContentLinearLayout.addView(titleTextView);

				// Plan Statement Text View
				TextView statementTextView = new TextView(
						getApplicationContext());
				statementTextView.setText(plan.getDesc());
				statementTextView.setTextSize(12);
				statementTextView.setBackgroundResource(R.color.string_color);
				statementTextView.setPadding(2, 0, 2, 0);

				// Add View //////////////////////////////////////////////
				planContentLinearLayout.addView(statementTextView);

				// Add View
				planRowLinearLayout.addView(planContentLinearLayout);

				// Add View
				planListLinearLayout.addView(planRowLinearLayout);

				Log.d("Plan", plan.getTitle());
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		// Initialize
		menuDialog = null;
		selectedIds = id;

		PlanDAO planDAO = null;
		PlanModel plan = null;
		try {
			planDAO = new PlanDAO(getApplicationContext());
			plan = planDAO.read(id);
		} catch (DatabaseConnectionException e) {
			e.printStackTrace();
		}
		planDAO.close();

		Log.d("Plan", plan.getTitle());
		Log.d("Plan", plan.getDesc());

		
		// Create Builer
		Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(plan.getTitle());

		// Create Items
		builder.setSingleChoiceItems(R.array.plan_alert_menu_array, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Log.d("Select", "" + which);
						seletedMenu = which;
					}
				});

		// Create OK
		builder.setPositiveButton(R.string.common_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Log.d("Select", "" + seletedMenu);

						Intent intent = null;

						switch (seletedMenu) {
						
						//Back to Menu
						case 0:
							intent = new Intent(ReadPlanActivity.this, VisionSoftwareMenuActivity.class);
							startActivity(intent);
						break;
						
						
						// Read Plan's Schedule
						case 1:
							intent = new Intent(ReadPlanActivity.this,
									ReadScheduleActivity.class);
							SharedPreferenceUtility.setPlanId(getApplicationContext(), selectedIds);
							startActivity(intent);
							break;
						
						// Create Plan's Schedule
						case 2:
							intent = new Intent(ReadPlanActivity.this,
									CreateScheduleActivity.class);
							SharedPreferenceUtility.setPlanId(getApplicationContext(), selectedIds);
							startActivity(intent);
							break;
							
						// Create Vision's Plan
						case 3:
							intent = new Intent(ReadPlanActivity.this,
									CreatePlanActivity.class);
							startActivity(intent);
							break;

						// Update Plan
						case 4:
							intent = new Intent(ReadPlanActivity.this,
									UpdatePlanActivity.class);
							startActivity(intent);
							break;

						// Delete Plan
						case 5:
							
							PlanDAO dao = null;
							try {
								dao = new PlanDAO(getApplicationContext());
								dao.delete(selectedIds);
							} catch (DatabaseConnectionException e) {
								e.printStackTrace();
							} catch (VisionUpdateException e) {
								e.printStackTrace();
							}
							dao.close();

							clearData(selectedIds);

							break;
						}

						// Set init value
						seletedMenu = -1;
					}
				});

		// Cancel Button
		builder.setNegativeButton(R.string.common_cancel, null);

		// Create Dialog
		menuDialog = builder.create();
		Log.d("Dialog", builder.toString());

		return menuDialog;
	}

	/**
	 * Load List Data
	 * 
	 * @param selectedIds
	 */
	private void clearData(int selectedIds) {
		int cnt = planListLinearLayout.getChildCount();
		Log.i("cnt", "" + cnt);

		for (int i = 0; i < cnt; i++) {
			View view = planListLinearLayout.getChildAt(i);
			Log.i("View", "" + view);

			if (view != null && view.getId() == selectedIds) {
				Log.i("plan Id", "" + view.getId());
				view.setVisibility(View.INVISIBLE);
				view.destroyDrawingCache();
				view.clearAnimation();
				view = null;
			}
		}
	}

	/**
	 * Load List Data
	 * 
	 * @throws VisionReadException
	 */
	private void loadListData() {
		PlanDAO dao = null;
		try {
			// Create DAO
			dao = new PlanDAO(getApplicationContext());

			// Read All
			list = dao.readAll();
		} catch (VisionReadException e) {
			e.printStackTrace();
		} catch (DatabaseConnectionException e) {
			e.printStackTrace();
		}
		
		dao.close();
	}
}